import { getProfileAPI, loginAPI } from '@/api/user'
import { TOKEN_KEY } from '@/constants/KEY'
import { getToken, removeToken, setToken } from '@/utils/auth'
import { routes, resetRouter } from '@/router/index'
export default {
  namespaced: true, // 开启命名空间
  state: () => {
    return {
      // 优先从本地取
      token: getToken() || '',
      profile: {}, // 用户信息
      menuList: [...routes]
    }
  },
  mutations: {
    setToken(state, token) {
      state.token = token
      // 本地存一份
      setToken(token)
    },
    clearUserInfo(state) {
      // 清除Token
      state.token = ''
      state.profile = {} // 清除用户信息
      removeToken(TOKEN_KEY)
    },
    // 设置用户信息
    setProfile(state, profile) {
      state.profile = profile
    },
    setMenuList(state, filterRoutes) {
      state.menuList = [...state.menuList, ...filterRoutes]
    },
    resetMenu(state) {
      // 重置左侧菜单
      state.menuList = routes
      // 重置路由系统
      resetRouter()
    }
  },
  actions: {
    async doLogin(ctx, { username, password }) {
      // 1. 调用接口
      const res = await loginAPI({ username, password })
      // 2. 提交mutation
      ctx.commit('setToken', res.data.token)
    },
    // 获取用户信息
    async getProfile(ctx) {
      const res = await getProfileAPI()
      ctx.commit('setProfile', res.data)
      return res.data
    }
  }
}
